CREATE FUNCTION get_risk_factor_for_client
(
	@client_id INT
)
RETURNS INTEGER

BEGIN
	DECLARE @risk_factor DECIMAL(9,2);
	DECLARE @invoices_total DECIMAL(9,2);
	DECLARE @invoices_count INT;

	SELECT @invoices_count  =COUNT(*),
		   @invoices_total = SUM(invoice_total)
	FROM invoices i
	WHERE i.client_id = client_id;

	SET @risk_factor = @invoices_total / @invoices_count * 5;

RETURN @risk_factor;
END;
------------------------------------------------------------------
SELECT
	client_id,
	name,
	dbo.get_risk_factor_for_client(client_id)
FROM clients